/**
  * This file is part of Medusa.
  *
  * Authors: Uriel Fanelli <uriel.fanelli@gmail.com>
  *          Perthect <perthect@gmail.com>
  *          Marco Bizzarri <Marco.Bizzarri@gmail.com>
  *
  *
  * Medusa is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.

  * Medusa is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.

  * You should have received a copy of the GNU General Public License
  * along with Medusa; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  */

#include <QUrl>
#include <QMessageBox>

#include "singletab.h"

//#include "myview.h"
#include "mainapp.h"

singleTab::singleTab(QWidget* parent)
    : QWebView(parent)
{
}

//singleTab::singleTab(QNetworkAccessManager *manager)
singleTab::singleTab(QWidget* parent,QNetworkAccessManager *manager)
{
    xpage = new QWebPage();
    setPage(xpage);
    xpage->setNetworkAccessManager(manager);
}

QTgoongress *singleTab::mainWindow()
{
    QObject *w = this->parent();
    while (w) {
        if (QTgoongress *mw = qobject_cast<QTgoongress*>(w))
            return mw;
        w = w->parent();
    }
}

QWebView *singleTab::createWindow(QWebPage::WebWindowType type)
{
    return mainWindow()->tWidget()->currentWebView()->view;  // OK POPUP IN SAME TAB
}

void singleTab::contextMenuEvent(QContextMenuEvent *event)
{
    QWebHitTestResult r = page()->mainFrame()->hitTestContent(event->pos());
    if (!r.linkUrl().isEmpty()) {
        link=r.linkUrl();
        QMenu menu(this);
        menu.addAction(pageAction(QWebPage::OpenLinkInNewWindow));
        menu.addAction(tr("Open in New Tab"), this, SLOT(openLinkInNewTab()));
        menu.addSeparator();
        menu.addAction(pageAction(QWebPage::DownloadLinkToDisk));
        menu.addAction(tr("Save link into *URIEL* folder"), this, SLOT(saveLinkIntoFolder()));
        menu.addAction(tr("URIEL IS BRITE"), this, SLOT(saveLinkIntoFolder()));
        menu.addAction(pageAction(QWebPage::DownloadLinkToDisk));
        menu.addSeparator();
        menu.addAction(pageAction(QWebPage::CopyLinkToClipboard));
        if (page()->settings()->testAttribute(QWebSettings::DeveloperExtrasEnabled))
            menu.addAction(pageAction(QWebPage::InspectElement));
        menu.exec(mapToGlobal(event->pos()));
        return;
    }
    QWebView::contextMenuEvent(event);
}

void singleTab::mostrapagina(QUrl url)
{
    load(url);
//    show();
}

singleTab::~singleTab()
{
//    delete this->view;
//    delete this->page;
}

void singleTab::httpRequestFinished(int requestId, bool error)
{
    if (requestId != httpGetId)
        return;
    if (httpRequestAborted) {
        if (file) {
            file->close();
            file->remove();
            delete file;
            file = 0;
        }
        progressDialog->hide();
        return;
    }
    if (requestId != httpGetId)
        return;
    progressDialog->hide();
    file->close();
    if (error) {
        file->remove();
        QMessageBox::information(this, tr("HTTP"),
                                 tr("Download failed: %1.")
                                 .arg(http->errorString()));
    }
    else {
        QString fileName = QFileInfo(QUrl(link).path()).fileName();
    }
    delete file;
    file = 0;
}

void singleTab::readResponseHeader(const QHttpResponseHeader &responseHeader)
{
     switch (responseHeader.statusCode()) {
     case 200:                   // Ok
     case 301:                   // Moved Permanently
     case 302:                   // Found
     case 303:                   // See Other
     case 307:                   // Temporary Redirect
         // these are not error conditions
         break;
     default:
         QMessageBox::information(this, tr("HTTP"),
                                  tr("Download failed: %1.")
                                  .arg(responseHeader.reasonPhrase()));
         httpRequestAborted = true;
         progressDialog->hide();
         http->abort();
     }
}

void singleTab::cancelDownload()
{
     httpRequestAborted = true;
     http->abort();
}

void singleTab::updateDataReadProgress(int bytesRead, int totalBytes)
{
    if (httpRequestAborted)
        return;
    progressDialog->setMaximum(totalBytes);
    progressDialog->setValue(bytesRead);
}

void singleTab::saveLinkIntoFolder()
{
    pageAction(QWebPage::DownloadLinkToDisk)->trigger();
    progressDialog = new QProgressDialog(this);
    connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
    http = new QHttp(this);
    QUrl url(link);
    QFileInfo fileInfo(url.path());
    QString fileName = fileInfo.fileName();
    if (fileName.isEmpty())
        fileName = "index.html";
    if (QFile::exists(fileName)) {
        if (QMessageBox::question(this, tr("HTTP"),
                                  tr("There already exists a file called %1 in "
                                  "the current directory. Overwrite?").arg(fileName),
                                  QMessageBox::Ok|QMessageBox::Cancel, QMessageBox::Cancel)
                                  == QMessageBox::Cancel)
            return;
        QFile::remove(fileName);
    }
    file = new QFile(fileName);
    connect(http, SIGNAL(requestFinished(int, bool)), this, SLOT(httpRequestFinished(int, bool)));
    connect(http, SIGNAL(dataReadProgress(int, int)), this, SLOT(updateDataReadProgress(int, int)));
    connect(http, SIGNAL(responseHeaderReceived(const QHttpResponseHeader &)), this, SLOT(readResponseHeader(const QHttpResponseHeader &)));
    connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
    if (!file->open(QIODevice::WriteOnly)) {
        QMessageBox::information(this, tr("HTTP"),
                                 tr("Unable to save the file %1: %2.")
                                 .arg(fileName).arg(file->errorString()));
        delete file;
        file = 0;
        return;
    }
    QHttp::ConnectionMode mode = url.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
    http->setHost(url.host(), mode, url.port() == -1 ? 0 : url.port());
    if (!url.userName().isEmpty())
        http->setUser(url.userName(), url.password());
    httpRequestAborted = false;
    QByteArray path = QUrl::toPercentEncoding(url.path(), "!$&'()*+,;=:@/");
    if (path.isEmpty())
        path = "/";
    httpGetId = http->get(path, file);
    progressDialog->setWindowTitle(tr("Medusa - Download"));
    progressDialog->setLabelText(tr("Downloading %1.").arg(fileName));
}
void singleTab::openLinkInNewTab(bool b)
{
}
void singleTab::download(const QNetworkRequest &request, bool requestFileName)
{
}
